package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.commom.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author by jojo
 * @Date 2022/3/8
 * @Description
 */
@Service
@Slf4j
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存 或 取消 不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {
//        1. 校验参数 文章id不能为空  需要登录 不喜欢类型取值为 0 或 1
//        2. 查询行为实体数据
        //是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            log.error("需要登录后才可以操作不喜欢行为！！！");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer equipmentId = dto.getEquipmentId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), equipmentId);
//        3. 如果是 不喜欢操作 查询不喜欢行为是否存在
        String entryId = apBehaviorEntry.getId();
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(entryId));
        if (dto.getType().equals(ApUnlikesBehavior.Type.UNLIKE.getCode())) {
            ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
            if (one == null) {
                // 4. 如果不存在   添加不喜欢行为
                ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setEntryId(entryId);
                apUnlikesBehavior.setType(ApUnlikesBehavior.Type.UNLIKE.getCode());
                apUnlikesBehavior.setCreatedTime(new Date());
                mongoTemplate.save(apUnlikesBehavior);
            }
            return ResponseResult.okResult();
        } else {
           // 5. 如果是 取消不喜欢操作  删除对应的不喜欢数据
            mongoTemplate.remove(query,ApUnlikesBehavior.class);
            return ResponseResult.okResult();
        }
    }
}
